
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet
from meiduo_admin.paginators import MyPage
from meiduo_admin.serializers.sku_serializers import *

# 可选规格视图
class SPUSpecView(ListAPIView):
    queryset = SPUSpecification.objects.all()
    serializer_class = SpecModelSerializer

    def get_queryset(self):
        # TODO：如何在非视图函数中，获取路径关键字参数
        # TODO：答，self.kwargs记录保存路径关键字参数 -> self.kwargs = {"pk": 1}
        spu_id = self.kwargs.get('pk')  # 路径中的spu的主键
        # TODO：根据路径参数spu_id过滤出选中spu关联的规格查询集
        return self.queryset.filter(spu_id=spu_id)


# 可选SPU信息视图
class SPUSimpleView(ListAPIView):
    queryset = SPU.objects.all()
    serializer_class = SPUSimpleSerializer

# 三级分类视图
class SKUCategorieView(ListAPIView):
    queryset = GoodsCategory.objects.all()
    serializer_class = SKUCateModelSerializer

    def get_queryset(self):
        return self.queryset.filter(parent_id__gt=37) # 父级分类id大于37属于第三级分类


# SKU视图
class SKUGoodsView(ModelViewSet):
    queryset = SKU.objects.all()
    serializer_class = SKUModelSerializer
    pagination_class = MyPage

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            return self.queryset.filter(name__contains=keyword)
        return self.queryset.all()